package com.an.cloud.mygateway;

import lombok.Getter;
import lombok.Setter;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

/**
 * 我网关过滤器工厂
 *
 * @author: ANHE
 * @createDate: 2024/03/20
 * @version: 1.0.0
 */
@Component
public class MyGatewayFilterFactory extends AbstractGatewayFilterFactory<MyGatewayFilterFactory.Config> {

    /**
     * 我网关过滤器工厂
     *
     * @author: ANHE
     * @createDate: 2024/03/20
     * @version: 1.0.0
     */
    public MyGatewayFilterFactory() {
        super(MyGatewayFilterFactory.Config.class);
    }

    /**
     * 应用
     *
     * @param config 配置
     * @return {@link GatewayFilter }
     * @author: ANHE
     * @createDate: 2024/03/20
     * @version: 1.0.0
     */
    public GatewayFilter apply(MyGatewayFilterFactory.Config config) {
        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();
            System.out.println("进入了自定义的网关过滤器MyGatewayFilterFactory，status: " + config.getStatus());
            if (request.getQueryParams().containsKey("atguigu")) {
                return chain.filter(exchange);
            } else {
                exchange.getResponse().setStatusCode(HttpStatus.BAD_REQUEST);
                return exchange.getResponse().setComplete();
            }
        };
    }

    /**
     * 快捷字段顺序
     *
     * @return {@link List }<{@link String }>
     * @author: ANHE
     * @createDate: 2024/03/20
     * @version: 1.0.0
     */
    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("status");
    }

    /**
     * 配置
     * yml的配置
     *
     * @author: ANHE
     * @createDate: 2024/03/20
     * @version: 1.0.0
     */
    public static class Config {
        /**
         * 状态
         */
        @Getter
        @Setter
        private String status;
    }
}
